package com.ruoyi.permission.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.permission.Dao.*;
import com.ruoyi.permission.domain.*;
import com.ruoyi.permission.mapper.SerUnitUserMapper;
import com.ruoyi.permission.service.PermiService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/permi")
public class PermissionController {

    @Autowired
    private PermiService permiService;
    @Autowired
    private SerUnitUserMapper unitUserMapper;
    @Autowired
    private RedisCache redisCache;
    @GetMapping("/getUnitList")
    public AjaxResult getUnitList(){
        List<UnitPermiInfo> unitPermiInfos = permiService.selectAllUnitPermi();
        return AjaxResult.success(unitPermiInfos);
    }

    @GetMapping("/getUserListByUnitId")
    public AjaxResult getUserListByUnitId(int unitId){
        List<UnitPermiUserInfo> unitPermiUserInfos = permiService.selectUserListByUnitId(unitId);
        return AjaxResult.success(unitPermiUserInfos);
    }

    @GetMapping("/getFuncListByUnitId")
    public AjaxResult getFuncListByUnitId(int unitId){
        List<UnitPermiFuncInfo> unitPermiFuncInfos = permiService.selectFuncListByUnitId(unitId);
        return AjaxResult.success(unitPermiFuncInfos);
    }
    @GetMapping("/getBaseListByUnitId")
    public AjaxResult getBaseListByUnitId(int unitId){
        List<UnitPermiBaseInfo> unitPermiBaseInfos = permiService.selectBaseListByUnitId(unitId);
        return AjaxResult.success(unitPermiBaseInfos);
    }

    @GetMapping("/getBlockListByBaseId")
    public AjaxResult getBlockListByBaseId(int baseId){
        List<BasePermiBlockInfo> basePermiBlockInfos = permiService.selectBlockListByBaseId(baseId);
        return AjaxResult.success(basePermiBlockInfos);
    }

    @GetMapping("/getDeviceListByBlockId")
    public AjaxResult getDeviceListByBlockId(int blockId){
        List<BlockPermiDeviceInfo> blockPermiDeviceInfos = permiService.selectDeviceListByBlockId(blockId);
        return AjaxResult.success(blockPermiDeviceInfos);
    }

    @PostMapping("/insertUnitPermi")
    public AjaxResult insertUnitPermi(SerUnitPermi unitPermi){
        int i = permiService.insertUnit(unitPermi);
        if(i>0){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @PostMapping("/insertDevicePermi")
    public AjaxResult insertDevicePermi(SerDevicePermi devicePermi){
        int i = permiService.insertDevice(devicePermi);
        if(i > 0){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @PostMapping("/insertUnitPermiBase")
    public AjaxResult insertUnitPermiBase(UnitPermiBaseInfo unitBase){
        int i = permiService.insertUnitPermiBase(unitBase);
        if(i>0){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @PostMapping("/insertUnitPermiFunc")
    public AjaxResult insertUnitPermiFunc(SerUnitFunc unitFunc){
        int i = permiService.insertUnitPermiFunc(unitFunc);
        if(i == -1){
            return AjaxResult.error("添加失败，请检查是否存在该功能模块！");
        }else if(i == 0){
            return AjaxResult.error("添加失败");
        }else {
            return AjaxResult.success("添加成功");
        }
    }

    @PostMapping("/insertUnitPermiUser")
    public AjaxResult insertUnitPermiUser(SerUnitUser unitUser){
        int i = permiService.insertUnitPermiUser(unitUser);
        if(i == -1){
            return AjaxResult.error("添加失败，请检查是否存在该用户！");
        }else if(i == 0){
            return AjaxResult.error("添加失败");
        }else {
            return AjaxResult.success("添加成功");
        }
    }

    @PostMapping("/insertBasePermiBlock")
    public AjaxResult insertBasePermiBlock(BasePermiBlockInfo baseBlock){
        int i = permiService.insertBasePermiBlock(baseBlock);
        if(i>0){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @PostMapping("/insertBlockPermiDevice")
    public AjaxResult insertBlockPermiDevice(SerBlockDevice blockDevice){
        int i = permiService.insertBlockPermiDevice(blockDevice);
        if(i>0){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @PostMapping("/insertDevicePermiInsect")
    public AjaxResult insertDevicePermiInsect(Integer deviceId,String insectIds){
        //统计插入数量
        int count = 0;
        String[] insectIdList = insectIds.split(",");
        for(int i = 0;i<insectIdList.length;i++){
            SerDeviceInsect serDeviceInsect = new SerDeviceInsect().setDeviceId(deviceId).setInsectId(Integer.valueOf(insectIdList[i]));
            count = count + permiService.insertDevicePermiInsect(serDeviceInsect);
        }
        if(count == insectIdList.length) {
            return AjaxResult.success("添加成功");
        }else {
            return AjaxResult.error("添加失败，请检查是否存在该虫情权限！");
        }
    }
    @PostMapping("/insertInsectPermi")
    public AjaxResult insertInsectPermi(SerInsectPermi insectPermi){
        int i = permiService.insertInsectPermi(insectPermi);
        if(i>0){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @PostMapping("/deleteUnitPermiBase")
    public AjaxResult deleteUnitPermiBase(Integer baseId){
        int i = permiService.deleteUnitPermiBase(baseId);
        if(i>0){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @PostMapping("/deleteUnitPermiFunc")
    public AjaxResult deleteUnitPermiFunc(SerUnitFunc unitFunc){
        int i = permiService.deleteUnitPermiFunc(unitFunc);
        if(i>0){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }
    @PostMapping("/deleteUnitPermiUser")
    public AjaxResult deleteUnitPermiFunc(Integer userId){
        int i = permiService.deleteUnitPermiUser(userId);
        if(i>0){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @PostMapping("/deleteBasePermiBlock")
    public AjaxResult deleteBasePermiBlock(Integer blockId){
        int i = permiService.deleteBasePermiBlock(blockId);
        if(i>0){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @PostMapping("/deleteBlockPermiDevice")
    public AjaxResult deleteBlockPermiDevice(SerBlockDevice blockDevice){
        int i = permiService.deleteBlockPermiDevice(blockDevice);
        if(i>0){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @ApiOperation("更新单位信息")
    @PostMapping("/updateUnitInfo")
    public AjaxResult updateUnitInfo(SerUnitPermi unitPermi){
       int i =  permiService.updateUnitInfo(unitPermi);
       if(i>0){
           return AjaxResult.success("更新单位信息成功");
       }else {
           return AjaxResult.error("更新失败");
       }
    }

    @ApiOperation("更新基地信息")
    @PostMapping("/updateBaseInfo")
    public AjaxResult updateBaseInfo(SerBasePermi basePermi){
        int i = permiService.updateBaseInfo(basePermi);
        if(i>0){
            return AjaxResult.success("更新基地信息成功");
        }else {
            return AjaxResult.error("更新失败");
        }
    }

    @ApiOperation("更新地块信息")
    @PostMapping("/updateBlockInfo")
    public AjaxResult updateBlockInfo(SerBlockPermi blockPermi){
        int i = permiService.updateBlockInfo(blockPermi);
        if(i>0){
            return AjaxResult.success("更新地块信息成功");
        }else {
            return AjaxResult.error("更新失败");
        }
    }

    @ApiOperation("根据设备昵称模糊查询设备")
    @GetMapping("/selectDeviceByNickName")
    public AjaxResult selectDeviceByNickName(String nickName){
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        int userId= userIdL.intValue();
        AllPermiInfo allPeri = getAllPeri(userId);
        List<BaseBlockPermiDeviceInfo> devicePermiList = allPeri.getDevice_permi();
        List<DevicePermiInfo>devicePermiInfoList = new ArrayList<>();
        for(BaseBlockPermiDeviceInfo baseBlockPermiDeviceInfo : devicePermiList){
            if(baseBlockPermiDeviceInfo.getDeviceName().contains(nickName)){
                Integer deviceId = baseBlockPermiDeviceInfo.getDeviceId();
                String deviceName = baseBlockPermiDeviceInfo.getDeviceName();
                String deviceSerial = baseBlockPermiDeviceInfo.getDeviceSerial();
                String manualId = baseBlockPermiDeviceInfo.getManualId();
                String deviceType = baseBlockPermiDeviceInfo.getDeviceType();
                Integer typeId = baseBlockPermiDeviceInfo.getTypeId();
                Double longitude = baseBlockPermiDeviceInfo.getLongitude();
                Double latitude = baseBlockPermiDeviceInfo.getLatitude();
                String onlineState = baseBlockPermiDeviceInfo.getOnlineState();
                String area = baseBlockPermiDeviceInfo.getArea();
                Double battery = baseBlockPermiDeviceInfo.getBattery();
                String province = baseBlockPermiDeviceInfo.getProvince();
                Integer id = baseBlockPermiDeviceInfo.getId();
                DevicePermiInfo newDevicePermiInfo = new DevicePermiInfo().setId(id).setDeviceId(deviceId).setDeviceName(deviceName)
                        .setDeviceSerial(deviceSerial).setManualId(manualId).setDeviceType(deviceType).setTypeId(typeId)
                        .setLongitude(longitude).setLatitude(latitude).setOnlineState(onlineState).setArea(area).setBattery(battery)
                        .setProvince(province);
                devicePermiInfoList.add(newDevicePermiInfo);
            }
        }
        return AjaxResult.success(devicePermiInfoList);
    }

    @ApiOperation("更新设备信息,连表更新")
    @PostMapping("/updateDeviceInfo")
    public AjaxResult updateDeviceInfo(SerDevicePermi devicePermi){
        int i = permiService.updateDeviceInfo(devicePermi);
        if(i>0){
            return AjaxResult.success("更新设备信息成功");
        }else {
            return AjaxResult.error("更新失败");
        }
    }

    @ApiOperation("根据设备id获取虫情权限")
    @GetMapping("/getInsectPermiByDeviceId")
    public AjaxResult getInsectPermiByDeviceId(String Ids){
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        int userId= userIdL.intValue();
        if(userId!=1&&userId!=20) {
            return AjaxResult.success(permiService.selectInsectPermiByDeviceId(Ids));
        }else{
//            deviceIds=""时，则判断为admin，返回所有虫情权限
            return AjaxResult.success(permiService.selectInsectPermiByDeviceId(""));
        }
    }

    @ApiOperation("根据设备id获取获取详细的虫情信息,管理员使用")
    @GetMapping("/getInsectDetailByDeviceId")
    public AjaxResult getInsectDetailByDeviceId(Integer deviceId){
        DevicePermiInsectList devicePermiInsectList = permiService.selectInsectByDeviceId(deviceId);
        return AjaxResult.success(devicePermiInsectList);
    }

    @ApiOperation("根据登陆用户的token，获取他的功能权限和设备权限")
    @GetMapping("/getAllPermiList")
    public AjaxResult getAllPermiList(){
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        int userId= userIdL.intValue();
        AllPermiInfo allPeri = getAllPeri(userId);
        redisCache.setCacheObject(userId + "",allPeri);
        return AjaxResult.success(allPeri);
    }
    // 按条件查询一个用户的所有权限（角色(可能多个)循环查找+单独功能权限+单独设备权限+单独虫情权限）（app端使用）
    @GetMapping("/getAllUserPermiLstByCondition")
    public AjaxResult getAllUserRoleLstByCondition(UserIdDeviceType userIdDeviceType){
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        int userId= userIdL.intValue();
        if(getAllPeri(userId) == null){
            return AjaxResult.error("用户id不存在！");
        }
        else{
//            UserAllPermi userAllPermi = getAllPeri(user_id);
            AllPermiInfo userAllPermi = redisCache.getCacheObject(userId + "");
            List<UnitPermiFuncInfo> func = userAllPermi.getFunc_permi();
//            List<PermiUserDetailInfo> insect = userAllPermi.getInsect_permi();
            List<BaseBlockPermiDeviceInfo> device = userAllPermi.getDevice_permi();
            List<BaseBlockPermiDeviceInfo> selectDevice = new ArrayList<>();
//            System.out.println("test:"+ userIdDeviceType.getDeviceType());
            if(userIdDeviceType.getDeviceType()!=null && !userIdDeviceType.getDeviceType().isEmpty())
            {
                List<BaseBlockPermiDeviceInfo> selectDeviceByType = new ArrayList<>();
                for (BaseBlockPermiDeviceInfo baseBlockPermiDeviceInfo : device) {
                    if(baseBlockPermiDeviceInfo.getDeviceType().equals(userIdDeviceType.getDeviceType())){
                        selectDeviceByType.add(baseBlockPermiDeviceInfo);
                    }
                }
//                System.out.println("\nselectDeviceByType:"+selectDeviceByType);
                if((userIdDeviceType.getOnlineState()!=null && !userIdDeviceType.getOnlineState().isEmpty()) &&(userIdDeviceType.getDeviceName() ==null || userIdDeviceType.getDeviceName().isEmpty()))
                {
                    for (BaseBlockPermiDeviceInfo baseBlockPermiDeviceInfo : selectDeviceByType)
                    {
                        if (baseBlockPermiDeviceInfo.getOnlineState().equals(userIdDeviceType.getOnlineState()))
                        {
                            selectDevice.add(baseBlockPermiDeviceInfo);
                        }
                    }
                }
                else if ((userIdDeviceType.getOnlineState() ==null || userIdDeviceType.getOnlineState().isEmpty()) && (userIdDeviceType.getDeviceName() != null && !userIdDeviceType.getDeviceName().isEmpty()))
                {
                    for (BaseBlockPermiDeviceInfo baseBlockPermiDeviceInfo : selectDeviceByType) {
                        if (baseBlockPermiDeviceInfo.getDeviceName() != null) {
                            if (baseBlockPermiDeviceInfo.getDeviceName().contains(userIdDeviceType.getDeviceName()) ||
                                    baseBlockPermiDeviceInfo.getDeviceSerial().contains(userIdDeviceType.getDeviceName())) {
                                selectDevice.add(baseBlockPermiDeviceInfo);
                            }
                        }
                    }
                }
                else if((userIdDeviceType.getOnlineState() != null && !userIdDeviceType.getOnlineState().isEmpty()) && (userIdDeviceType.getDeviceName() != null && !userIdDeviceType.getDeviceName().isEmpty()))
                {
                    for(BaseBlockPermiDeviceInfo baseBlockPermiDeviceInfo : selectDeviceByType){
                        if(baseBlockPermiDeviceInfo.getOnlineState().equals(userIdDeviceType.getOnlineState()) &&(baseBlockPermiDeviceInfo.getDeviceName().contains(userIdDeviceType.getDeviceName())||
                                baseBlockPermiDeviceInfo.getDeviceSerial().contains(userIdDeviceType.getDeviceName())))
                        {
                            selectDevice.add(baseBlockPermiDeviceInfo);
                        }
                    }
                }
                else {
                    selectDevice.addAll(selectDeviceByType);
                }
            }else {
                selectDevice.addAll(device);
            }
            Comparator<BaseBlockPermiDeviceInfo> statusComparator = Comparator.comparingInt(this::getStatusOrder);
            // 使用比较器对数据进行排序
            Collections.sort(selectDevice, statusComparator);
            System.out.println("\nselectDevice:" + selectDevice);
            AllPermiInfo userAllPermiRes = new AllPermiInfo(userId,func, selectDevice);
            return AjaxResult.success(userAllPermiRes);
        }
    }
    // 自定义方法返回status属性的顺序值
    private int getStatusOrder(BaseBlockPermiDeviceInfo obj) {
        String status = obj.getOnlineState();
        if (status.equals("在线")) {
            return 1;
        } else if (status.equals("休眠")) {
            return 2;
        } else if (status.equals("离线")) {
            return 3;
        } else {
            return 0; // 如果有未知的状态，可以放在最后
        }
    }
    private AllPermiInfo getAllPeri(int userId){

        log.info("userID" + userId);
//        int userId = 1;
        //管理员默认无单位，单位id就设为0
        Integer unitId = 0;
        if(userId != 1 && userId != 20) {
            unitId = unitUserMapper.selectByPrimaryKey(userId).getUnitId();
        }
        List<BaseBlockPermiDeviceInfo> baseBlockPermiDeviceInfoList = permiService.selectAllDeviceByUnitId(unitId);
        List<UnitPermiFuncInfo> unitPermiFuncInfoLst = permiService.selectFuncListByUnitId(unitId);
        AllPermiInfo allPermiInfo = new AllPermiInfo().setUserId(userId).setDevice_permi(baseBlockPermiDeviceInfoList).setFunc_permi(unitPermiFuncInfoLst);
        return allPermiInfo;
    }
    @ApiOperation("查询每种设备的总数量、在线数量和休眠数量")
    @GetMapping("/countOnlineDevice")
    public AjaxResult countOnlieDevice(){
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        int userId= userIdL.intValue();
        //管理员默认无单位，单位id就设为0
        Integer unitId = 0;
        if(userId != 1 && userId != 20) {
            unitId = unitUserMapper.selectByPrimaryKey(userId).getUnitId();
        }
        List<BaseBlockPermiDeviceInfo> baseBlockPermiDeviceInfoList = permiService.selectAllDeviceByUnitId(unitId);
        //用于统计最终的设备在线数量的列表
        List<DeviceTypeAndNum> resLst = new ArrayList<>();
        //用于统计各个设备种类的数量
        Map<String, Integer> deviceTypeCount = new HashMap<>();
//            用于统计各个设备种类的在线数量
        Map<String, Integer> deviceTypeOnlineCount = new HashMap<>();
//            用于统计各个设备种类的休眠数量
        Map<String,Integer> deviceTypeSleepCount = new HashMap<>();

        for(BaseBlockPermiDeviceInfo blockPermiDeviceInfo:baseBlockPermiDeviceInfoList){
            String deviceType = blockPermiDeviceInfo.getDeviceType();
//                统计设备数量
            if(deviceTypeCount.containsKey(deviceType)){
                int count = deviceTypeCount.get(deviceType);
                deviceTypeCount.put(deviceType,count + 1);
            }else{
                deviceTypeCount.put(deviceType,1);
            }
//                统计在线设备数量和休眠设备数量
            String onlineState = blockPermiDeviceInfo.getOnlineState();
            if (onlineState.equals("在线")) {
                if (deviceTypeOnlineCount.containsKey(deviceType)) {
                    int count = deviceTypeOnlineCount.get(deviceType);
                    deviceTypeOnlineCount.put(deviceType, count + 1);
                } else {
                    deviceTypeOnlineCount.put(deviceType, 1);
                }
            }else if(onlineState.equals("休眠")){
                if(deviceTypeSleepCount.containsKey(deviceType)){
                    int count = deviceTypeSleepCount.get(deviceType);
                    deviceTypeSleepCount.put(deviceType,count + 1);
                }else{
                    deviceTypeSleepCount.put(deviceType,1);
                }
            }
        }
        for(Map.Entry<String,Integer>entry:deviceTypeCount.entrySet()){
            DeviceTypeAndNum deviceTypeAndNum = new DeviceTypeAndNum();
            String deviceType = entry.getKey();
            int deviceCount = entry.getValue();
            int onlineCount = deviceTypeOnlineCount.getOrDefault(deviceType,0);
            int sleepCount = deviceTypeSleepCount.getOrDefault(deviceType,0);
            deviceTypeAndNum.setDeviceType(deviceType).setTotal(deviceCount).setOnlineNum(onlineCount).setSleepNum(sleepCount);
            resLst.add(deviceTypeAndNum);
        }
        return AjaxResult.success(resLst);
    }



}
